package com.hmsm.sys.daoImpl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.hmsm.server.base.BaseDao;
import com.hmsm.sys.dao.UserRoleDao;
import com.hmsm.sys.dto.UserDto;
import com.hmsm.sys.po.UserRole;

/**
 * 用户角色信息
 * 
 * @author 舒俊
 *
 *@version 1.0, 2012-11-29 下午04:47:24
 */
@Repository
public class UserRoleDaoImpl extends BaseDao<UserRole, Integer> implements UserRoleDao {
	
	/**
	 * 用户角色
	 */
	@SuppressWarnings("unchecked")
	public List<UserDto> queryUserRoleByRoleId(int roleId){
		String hql = " select new com.hmsm.sys.dto.UserDto(c.pkId,c.name,c.userName,c.userDept) from UserInfo c, UserRole c1 where c1.userId = c.pkId and c.state = 1 and c1.state = 1 and c1.roleId = "+roleId+" ";
		return this.getHibernateTemplate().find(hql);
	}


	@Override
	public List<Integer> getRoleIdsByUserId(final Integer userId) {
		Set<Integer> roleIds = new HashSet<Integer>();
		
		List<UserRole> obj = getHibernateTemplate().execute(new HibernateCallback<List<UserRole>>(){
			@Override
			public List<UserRole> doInHibernate(Session session) throws HibernateException, SQLException {
				List<UserRole> list = (List<UserRole>)(session.createCriteria(UserRole.class).add(Restrictions.eq("userId", userId)).add(Restrictions.eq("state", 1)).list());
				session.close();
				return list;
			}
		});
		for (UserRole userRole:(List<UserRole>) obj){
			roleIds.add(userRole.getRoleId());
		}
		
		return new ArrayList<Integer>(roleIds);
	}
	
}
